<template>
  <div class="document-reader">
    <el-card class="reader-card">
      <template #header>
        <div class="card-header">
          <span>{{ document.title || '文档阅读器' }}</span>
        </div>
      </template>

      <div class="document-content">
        <div class="content-text" @mouseup="handleTextSelection" v-html="document.content"></div>

        <!-- Hidden audio element for pronunciation playback -->
        <audio id="document-reader-audio" style="display: none"></audio>

        <!-- Word Definition Panel -->
        <WordDetails :word="selectedWord" />
        
        <WordPronunciation
          :word="selectedWord"
          :is-playing="isPlaying"
          @play="playPronunciation"
          @stop="stopPronunciation"
        />

        <div style="margin-top: 15px;">
          <el-button
            size="small"
            :type="selectedWord.ok === 'YES' ? 'warning' : 'info'"
            @click="toggleWordStatus"
          >
            {{ selectedWord.ok === 'YES' ? '标记为未掌握' : '标记为已掌握' }}
          </el-button>
          
          <el-tag
            v-if="selectedWord.ielst === 'YES'"
            type="success"
            size="small"
            effect="dark"
            style="margin-left: 10px;"
          >
            雅思词汇
          </el-tag>
        </div>

        <div style="margin-top: 10px">
          <el-button size="small" @click.stop="addToVocabulary" type="primary">
            <el-icon><Plus /></el-icon> 添加到生词本
          </el-button>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
import WordDetails from './WordDetails.vue';
import WordPronunciation from './WordPronunciation.vue';
import { updateWordStatus } from '../utils';

export default {
  name: 'DocumentReader',
  components: {
    WordDetails,
    WordPronunciation
  },
  props: {
    document: {
      type: Object,
      required: true,
    },
  },
  data() {
    return {
      selectedWord: null,
      activeCollapse: ['definition'],
      isPlaying: false
    };
  },
  methods: {
    handleTextSelection() {
      const selection = window.getSelection();
      if (selection && selection.toString().trim()) {
        const selectedText = selection.toString().trim();
        // Check if selected text is a single English word
        if (/^[a-zA-Z]+$/.test(selectedText)) {
          this.lookupWord(selectedText);
        }
      }
    },

    async lookupWord(word) {
      try {
        // Check if electronAPI is available
        if (typeof window.electronAPI !== 'undefined' && window.electronAPI.getWord) {
          const response = await window.electronAPI.getWord(word);

          if (response.success && response.data) {
            this.selectedWord = response.data;
            this.$emit('word-selected', this.selectedWord);
          } else {
            // If word not found, create a basic word object
            this.selectedWord = {
              word: word,
              phonetic: '',
              trans: '未找到该单词',
              ielst: 'NO',
              ok: 'NO',
            };
            this.$emit('word-selected', this.selectedWord);
          }
        } else {
          console.warn('Electron API not available, running in browser development mode');
          // For development, simulate a word lookup
          this.selectedWord = {
            word: word,
            phonetic: `[${word}]`,
            trans: `单词 "${word}" 的翻译`,
            ielst: Math.random() > 0.7 ? 'YES' : 'NO', // Randomly mark some words as IELTS words
            ok: Math.random() > 0.5 ? 'YES' : 'NO', // Randomly mark some words as known
          };

          this.$emit('word-selected', this.selectedWord);
        }
      } catch (err) {
        console.error('Error looking up word:', err);
        this.$message.error('查询单词失败: ' + err.message);
      }
    },

    async toggleWordStatus() {
      if (this.selectedWord) {
        await updateWordStatus(this.selectedWord, {
          success: (msg) => this.$message.success(msg),
          error: (msg) => this.$message.error(msg)
        });
      }
    },

    async playPronunciation() {
      if (this.selectedWord) {
        try {
          this.isPlaying = true;
          
          // Check if electronAPI is available
          if (typeof window.electronAPI !== 'undefined' && window.electronAPI.playPronunciation) {
            // Get the pronunciation path from the word data
            let audioPath = this.selectedWord.uk_speech || this.selectedWord.us_speech;

            if (audioPath) {
              // Process the audio path to handle escaped characters
              console.log('Raw audio path:', audioPath);
              // Remove surrounding quotes if present
              if (audioPath.startsWith('"') && audioPath.endsWith('"')) {
                audioPath = audioPath.slice(1, -1);
              }

              // Fix escaped forward slashes
              audioPath = audioPath.replace(/\\\//g, '/');
              console.log('Processed audio path:', audioPath);

              // Use HTML5 audio element for playback
              const audioElement = document.getElementById('document-reader-audio');
              if (audioElement) {
                audioElement.src = audioPath;
                await audioElement.play();
                this.$message.success(`正在播放发音: ${this.selectedWord.word}`);
              } else {
                this.$message.error('无法播放音频');
              }
            } else {
              this.$message.warning('该单词没有发音资源');
            }
          } else {
            console.warn('Electron API not available, running in browser development mode');
            this.$message.success(`播放发音: ${this.selectedWord.word}`);
          }
        } catch (err) {
          console.error('Error playing pronunciation:', err);
          this.$message.error('播放发音失败: ' + err.message);
        } finally {
          this.isPlaying = false;
        }
      }
    },

    async addToVocabulary() {
      if (this.selectedWord) {
        try {
          // Check if electronAPI is available
          // In a real implementation, we might have a specific API for adding to vocabulary
          // For now, we'll just show a success message
          this.$message.success(`已添加 "${this.selectedWord.word}" 到生词本`);
          this.selectedWord = null;
          window.getSelection().removeAllRanges();
        } catch (err) {
          console.error('Error adding to vocabulary:', err);
          this.$message.error('添加到生词本失败: ' + err.message);
        }
      }
    },
  },
};
</script>

<style scoped>
.document-reader {
  max-width: 800px;
  margin: 0 auto;
}

.document-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  font-weight: 600;
  font-size: 18px;
  color: #333;
}

.document-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.document-text {
  min-height: 300px;
  padding: 20px;
  border: 1px solid #e6e6e6;
  border-radius: 4px;
  background-color: #fff;
  line-height: 1.6;
  cursor: text;
}

.document-text:focus {
  outline: none;
  border-color: #409eff;
}

.no-content {
  color: #999;
  font-style: italic;
  text-align: center;
  padding: 50px 0;
}

.word-panel {
  margin-top: 20px;
}

.word-translation,
.word-phonetic {
  margin: 10px 0;
}
</style>
